// Copyright  2012 Petr TALLA. [petr.talla@gmail.com]
// This file is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY;  without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
// [http://www.gnu.org/copyleft/lesser.html]
//=============================================================================
package tc.map;
import java.util.Iterator;
import java.util.LinkedList;
import java.awt.Image;
import java.net.URL;

import java.net.URL;
import java.net.URLConnection;
import java.util.Map.Entry;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.SwingUtilities;

//=============================================================================
/**Tile loader thread. Now it loads tiles sequentially, it will become job dispatcher
in future. It communicates with main application using TcTileLoaderMediator only.
*/
public class TcTileLoaderThread extends Thread {
//=============================================================================	
private TcTileLoaderMediator mainToDispatchMediator;

public TcTileLoaderThread(TcTileLoaderMediator mainToDispatchMediator)
{	this.mainToDispatchMediator = mainToDispatchMediator;
}

//=============================================================================
public void run()
{	while(true)
	{	TcTile tile = mainToDispatchMediator.nextTileToProcess();		
		if (tile == null) {
			try {
				sleep(50);
			}
			catch (Exception e) {
			}
		}
		else {
			singleStep(tile);
		}
	}
}

private void singleStep(TcTile tile) {
	String urlStr;
	
	synchronized (tile)
	{	urlStr = TcMviewControl.httpbase + tile.getAddress().toString() + ".png"; //TODO - locking
	}
						
	try	{	
		URL url = new URL(urlStr);
			
		URLConnection conn = url.openConnection();
		conn.setConnectTimeout(30000);
		conn.setReadTimeout(30000);
		conn.connect();
		InputStream is=conn.getInputStream();
		Image image = ImageIO.read(is);
		
		tile.updateImage(image); //method is synchronized
		
		mainToDispatchMediator.updateView();
		
		if ( TcMviewControl.DEBUG_DRAWING ) { 
			System.out.printf("LOADED: %s REMAINS: %d\n", tile.getAddress().toString(),
					mainToDispatchMediator.dirtyTilesSize());
		}
	}
	catch (IOException e) {
		System.out.printf("IOException:\n%s\n", urlStr);
	}
	/*catch (InterruptedException e)  {
		System.out.printf("Interupted exception: %s\n", urlStr);
	}*/
}
//=============================================================================
}
